#!/bin/sh
# eotk (c) 2019 Alec Muffett

# IMPORTANT NOTE: THIS SCRIPT MUST BE INDIVIDUALLY INSTALLED/ENABLED ON EVERY MACHINE RUNNING EOTK

# The general thinking here is:
#
# 1) you create the script by using:
#
#   eotk make-scripts
#
# 2) copy/symlink it into the relevant system; e.g. for Linux
#    you will probably do something like:
#
#   sudo cp eotk-init.sh /etc/init.d && sudo update-rc.d eotk-init.sh defaults
#
# If you want logging to appear elsewhere, redefine log_message()

### BEGIN INIT INFO
# Provides:          eotk
# Required-Start:    $local_fs $network $named $time $syslog
# Required-Stop:     $local_fs $network $named $time $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Description:       Enterprise Onion Toolkit
### END INIT INFO

# Let's factor these out in case of manual editing, although moving
# configured projects around the filesystem will be challenging;
# easier instead to configure in-situ and as the intended user.

EOTK_HOME=%EOTK_HOME%
EOTK_USER=%USER% # hardcode owner of the directory & files
EOTK_INIT_LOG=/tmp/eotk-init.log
EOTK_OB_DELAY=90 # backgrounded pause

exec </dev/null >>$EOTK_INIT_LOG 2>&1

date # help with debugging

# log_message: you might want to wire this into syslog, etc...

log_message() {
    echo "$@" 1>&2
}

# eotk wrapper

run_eotk() {
    sudo -u $EOTK_USER $EOTK_HOME/eotk --boot "$@"
    return $?
}

# does EOTK exist?

[ -d "$EOTK_HOME" ] || exit 0

cd $EOTK_HOME || exit 1

# just the basics; if it exists, start/stop it.

case "$1" in
    start)
        log_message Starting EOTK
	run_eotk start -a || exit 1
	if [ -d $EOTK_HOME/onionbalance.d ] ; then
            log_message Backgrounding start for EOTK OnionBalance
            # stdout should already be a file because of `exec` above
            ( ( sleep $EOTK_OB_DELAY && run_eotk ob-start -a ) & ) & # old-skool nohup
        fi
        log_message Started EOTK
	;;

    restart)
        log_message Restarting EOTK
	run_eotk restart -a || exit 1
	if [ -d $EOTK_HOME/onionbalance.d ] ; then
            run_eotk ob-restart -a || exit 1
        fi
        log_message Restarted EOTK
	;;

    stop)
        log_message Stopping EOTK
	run_eotk shutdown # does everything
        log_message Stopped EOTK
	;;

    *)
	echo "Usage: $0 {start|stop|restart}"
	exit 1
	;;
esac

# done

exit 0
